package com.swd.order.service;


import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.swd.order.model.User;
import com.swd.order.model.WxNotifyModel;
import com.swd.order.util.HttpUtil;
import com.swd.order.util.WxProperties;
import com.swd.order.util.WxUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class WxService {


    @Autowired
    private WxProperties wxProperties;

    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    private WxUtil wxUtil;

    public String getAccessToken() {

//        String accessToken = wxUtil.getAccessToken();

//        if (!StringUtils.isEmpty(accessToken)) {
//            log.info("access_token已存在,取缓存");
//            return accessToken;
//        }


        Map<String, String> map = new HashMap<>();
        map.put("grant_type", wxProperties.getGrant_type());
        map.put("appid", wxProperties.getAppid());
        map.put("secret", wxProperties.getSecret());

        JsonNode jsonNode;

        try {
            HttpEntity request = HttpUtil.getRequest(wxProperties.getGetAccessTokenUrl(), map);
            jsonNode = objectMapper.readTree(EntityUtils.toString(request));
        } catch (Exception e) {
            log.error("获取getAccessToken失败", e);
            return null;
        }
        log.info(jsonNode.toString());
        if (StringUtils.isEmpty(jsonNode.get("access_token").asText())) {
            log.error("获取getAccessToken失败{}", jsonNode.toString());
            return null;
        }
//        log.info("access_token缓存值");
//        wxUtil.setAccessToken(jsonNode.get("access_token").asText());
        return jsonNode.get("access_token").asText();
    }

    public String getJXAccessToken() {

        Map map = new HashMap();
        map.put("grant_type", "client_credential");
        map.put("appid", wxProperties.getGzhappid());
        map.put("secret", wxProperties.getGzhsecret());

        try {
            HttpEntity entity = HttpUtil.getRequest("https://api.weixin.qq.com/cgi-bin/token",
                    map);
            String s = EntityUtils.toString(entity);
            log.info(s);
            return objectMapper.readTree(s).get("access_token").asText();
        } catch (Exception e) {
            log.error("获取openId失败", e);
            return null;
        }

    }

    public String getOpenId(String code) {
        Map map = new HashMap();
        map.put("appid", wxProperties.getAppid());
        map.put("secret", wxProperties.getSecret());
        map.put("js_code", code);
        map.put("grant_type", "authorization_code");
        try {

            HttpEntity entity = HttpUtil.getRequest(wxProperties.getGetOpenIdUrl(), map);
            String s = EntityUtils.toString(entity);
            log.info(s);
            return objectMapper.readTree(s).get("openid").asText();

        } catch (Exception e) {
            log.error("获取openId失败", e);
            return null;
        }
    }

    public boolean subscribeMessageSend(int orderId, String openId, String templateId,Map map) {

        WxNotifyModel wxNotifyModel = WxNotifyModel.WxNotifyBuild(openId, templateId, map,
                "pages/order/orderDetail?id=" + orderId, wxProperties.getAppType());

        log.info(wxNotifyModel.toString());

        Map urlMap = new HashMap();
        urlMap.put("access_token", getAccessToken());
        try {
            HttpEntity entity = HttpUtil.postJsonRequest(wxProperties.getSendUrl(), urlMap,
                    objectMapper.writeValueAsString(wxNotifyModel));
            String s = EntityUtils.toString(entity);
            log.info(s);
        } catch (Exception e) {
            log.error("推送失败", e);
        }
        return true;
    }


    public boolean sendCreateMessage(User orderUser,User user, String remark, String jxAccessToken,Integer orderId) {

        Map<String, String> map = new HashMap<>();
        map.put("first", "点餐通知");
        map.put("keyword1", StringUtils.isEmpty(orderUser.getName()) ? orderUser.getWxName():orderUser.getName());
        map.put("keyword2", "请进入小程序查看");
        map.put("keyword3", "￥0.00");
        map.put("keyword4", "无");
        map.put("remark", remark);

        WxNotifyModel wxNotifyModel = WxNotifyModel.WxGZHNotifyBuild(user.getNotifyOpenid(),
                "CZYRAYZR2lFLilYVOZxiuAIQCLAm7SPBwUSdiUnZtLo", map,wxProperties.getAppid(),"pages/order/orderDetail?id=" + orderId);
        log.info(wxNotifyModel.toString());

        Map urlMap = new HashMap();
        urlMap.put("access_token",jxAccessToken);
        try {
            HttpEntity entity = HttpUtil.postJsonRequest("https://api.weixin.qq.com/cgi-bin/message/template/send",
                    urlMap,
                    objectMapper.writeValueAsString(wxNotifyModel));
            String s = EntityUtils.toString(entity);
            log.info(s);
        } catch (Exception e) {
            log.error("推送失败", e);
        }
        return true;
    }

    public boolean sendMealMessage(String openId,String jxAccessToken,Integer orderId) {

        Map<String, String> map = new HashMap<>();
        map.put("first", "就餐通知");
        map.put("keyword1", "就餐通知");
        map.put("keyword2", "就餐通知");
        map.put("keyword3", "就餐通知");
        map.put("keyword4", "就餐通知");
        map.put("remark", "就餐通知");

        WxNotifyModel wxNotifyModel = WxNotifyModel.WxGZHNotifyBuild(openId,
                "CZYRAYZR2lFLilYVOZxiuAIQCLAm7SPBwUSdiUnZtLo", map,wxProperties.getAppid(),"pages/order/orderDetail?id=" + orderId);
        Map urlMap = new HashMap();
        urlMap.put("access_token",jxAccessToken);
        try {
            HttpEntity entity = HttpUtil.postJsonRequest("https://api.weixin.qq.com/cgi-bin/message/template/send",
                    urlMap,
                    objectMapper.writeValueAsString(wxNotifyModel));
            String s = EntityUtils.toString(entity);
            log.info(s);
        } catch (Exception e) {
            log.error("推送失败", e);
        }
        return true;
    }


//    public
}
